package com.chen.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
public class IndexController {

    //跳转到主页面
    @RequestMapping({"/","/index"})
    public String index(){

        return "index";
    }

    //用户登录
    @RequestMapping("/login")
    public String login(String username, String password, Model model, HttpServletRequest request){

        //获取当前对象
        Subject subject = SecurityUtils.getSubject();
        //验证用户名和密码
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //token.setRememberMe(true);记住我
        //登陆失败捕捉异常
        try {
            subject.login(token);

        } catch ( UnknownAccountException uae ) {
            model.addAttribute("msg","用户名错误！");
            return "index";
        } catch ( IncorrectCredentialsException ice ) {
            model.addAttribute("msg","密码错误！");
            return "index";
        }

       request.getSession().setAttribute("username",username);

        return "admin/dashboard";
    }


    @RequestMapping("/dash")
    public String toDash(){
        return "admin/dashboard";
    }

    //退出
    @RequestMapping("/logout")
    public String logout(){

        Subject subject = SecurityUtils.getSubject();
        if (subject!=null){
            subject.logout();
        }
        return "redirect:index";
    }


    //未授权页面

    @RequestMapping("/unauth")
    @ResponseBody
    public String unauthorized(){
        return "抱歉，您没有权限操作！";
    }
}
